/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import 'intersection-observer';
import { isArray } from 'lodash';
import { useEffect } from 'react';
import { IntersectionObserverCallback, ObserverDomParams } from './types';

export function useObserverDom(callback: IntersectionObserverCallback, params: ObserverDomParams) {
  const { rootRef, actionRef, queryRef, opts, intersectionRatio } = params;
  useEffect(() => {
    const node = queryRef?.current || actionRef?.current;
    if (!node) {
      callback();
      return;
    }
    const { threshold } = opts || {};
    let thresholds: number[] = [0, 1];
    if (threshold) {
      if (isArray(threshold)) {
        thresholds = thresholds.concat(threshold);
      } else {
        // @ts-ignore
        thresholds.push(threshold);
      }
    }
    if (intersectionRatio) {
      thresholds.push(intersectionRatio);
    }

    const ins = new IntersectionObserver(
      (entries, observer) => callback({ entries, observer, node }),
      {
        ...opts,
        threshold: thresholds,
        root: rootRef?.current,
      },
    );
    ins.observe(node);
    return () => {
      ins.unobserve(node);
      ins.disconnect();
    };
  }, []);
}
